package com.sky.service.user.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.mapper.user.ShoppingCartMapper;
import com.sky.mapper.user.UDishMapper;
import com.sky.mapper.user.USetmealMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.Setmeal;
import com.sky.pojo.ShoppingCart;
import com.sky.service.user.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UDishMapper uDishMapper;
    @Autowired
    private USetmealMapper uSetmealMapper;

    @Override
    public int add(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        shoppingCart.setUserId(2L);

        List<ShoppingCart> list = shoppingCartMapper.listOne(shoppingCart);
        //不为空，说明购物车已经存在
        if(list != null&&list.size()==1){
            shoppingCart = list.get(0);
            shoppingCart.setNumber(shoppingCart.getNumber()+1);
            shoppingCartMapper.updateNumber(shoppingCart);
        }else{
            Long dishId = shoppingCart.getDishId();
            if(dishId != null){
                Dish byId = uDishMapper.getById(dishId);
                shoppingCart.setName(byId.getName());
                shoppingCart.setAmount(byId.getPrice());
                shoppingCart.setImage(byId.getImage());
            }else {
                Long setmealId = shoppingCartDTO.getSetmealId();
                Setmeal byId = uSetmealMapper.getById(setmealId);
                shoppingCart.setName(byId.getName());
                shoppingCart.setAmount(byId.getPrice());
                shoppingCart.setImage(byId.getImage());
            }
        }
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
        int add = shoppingCartMapper.add(shoppingCart);
        return add;
    }

    @Override
    public List<ShoppingCart> list() {
        return shoppingCartMapper.list(2L);
    }

    @Override
    public int clean() {
        int clean = shoppingCartMapper.clean(2L);
        return clean;
    }
}
